﻿package mlc.avm2.visualizing;
import haxe.PosInfos;
import mlc.avm2.visualizing.writetarget.WriteTarget;
import mlc.haxe.output.ConsoleOutputHandler;

/**
 * The output handler used by the AVM2 console visualizer.
 */
class AVM2ConsoleVisualizerOutputHandler implements ConsoleOutputHandler {
	private static inline var BOOL_COLOR:UInt = 0x98ABFB;
	private static inline var NUMERAL_COLOR:UInt = 0x89FF89;
	private static inline var STRING_COLOR:UInt = 0xFFFFFF;
	public var target(default, setTarget):WriteTarget;
	private var xmlPrettyPrinter:XMLPrettyPrinter;
	/**
	 * Creates a new AVM2 console visualizer output handler.
	 */
	public function new(target:WriteTarget):Void {
		xmlPrettyPrinter = new XMLPrettyPrinter();
		this.target = target;
	}
	public function clearOutput():Void {
		target.clearOutput();
	}
	private inline function setTarget(value:WriteTarget):WriteTarget {
		return xmlPrettyPrinter.target = target = value;
	}
	public function writeAdvancedString(value:String, color:Int, breakline:Bool):Void {
		target.write(value, color, breakline);
	}
	public function writeBool(value:Bool, positionInformation:PosInfos):Void {
		writePositionInformationPrefix(positionInformation);
		target.write(Std.string(value), BOOL_COLOR, true);
	}
	public function writeFloat(value:Float, positionInformation:PosInfos):Void {
		writePositionInformationPrefix(positionInformation);
		target.write(Std.string(value), NUMERAL_COLOR, true);
	}
	public function writeInt(value:Int, positionInformation:PosInfos):Void {
		writePositionInformationPrefix(positionInformation);
		target.write(Std.string(value), NUMERAL_COLOR, true);
	}
	public function writeNull(positionInformation:PosInfos):Void {
		writePositionInformationPrefix(positionInformation);
		target.write("null", BOOL_COLOR, true);
	}
	private inline function writePositionInformationPrefix(value:PosInfos):Void {
		// Write the file name without the ".hx" suffix, and the line in parentheses.
		target.write(value.fileName.substr(0, value.fileName.length - 3) + " (line " + value.lineNumber + "): ", 0xFFFFFF, false);
	}
	public function writeString(value:String, positionInformation:PosInfos):Void {
		writePositionInformationPrefix(positionInformation);
		target.write(value, STRING_COLOR, true);
	}
	public inline function writeXml(value:Xml, positionInformation:PosInfos):Void {
		writePositionInformationPrefix(positionInformation);
		xmlPrettyPrinter.writeXml(value);
	}
}